﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;

namespace CateringCommon
{
    public class Common
    {
        #region Public
        public static string GetUserToken(string userName, string passWd)
        {
            return GetMD5Hash(userName + passWd);
        }

        public static bool Login(string userName, string passWd)
        {
            return Login(userName, passWd, null);
        }

        public static bool Login(string userName, string passWd, HttpContext httpContext)
        {
            string userToken = GetUserToken(userName, passWd);
            //TODO：查询数据库比较并获取用户基本信息

            if (userToken == "")
            {
                if (httpContext != null)
                {
                    //TODO：构造用户上下文，并放到Session里

                    UserContext userContext = new UserContext();
                    userContext.UserName = userName;

                    httpContext.Session["UserContext"] = userContext;

                }
                return true;
            }
            return false;
        }

        public static UserContext InitUserContext(HttpContext httpContext)
        {
            UserContext userContext = null;
            if (httpContext.Session["UserContext"] is UserContext)
            {
                userContext = httpContext.Session["UserContext"] as UserContext;
            }
            return userContext;
        }
        #endregion

        #region Private
        private static string GetMD5Hash(string strSource)
        {
            string strResult = "";
            string strHashData = "";
            byte[] arrbytHashValue;
            MD5CryptoServiceProvider oMD5Hasher = new MD5CryptoServiceProvider();

            try
            {
                arrbytHashValue = oMD5Hasher.ComputeHash(Convert.FromBase64String(strSource));
                //由以连字符分隔的十六进制对构成的String，其中每一对表示value 中对应的元素；例如“F-2C-4A”
                strHashData = System.BitConverter.ToString(arrbytHashValue);
                //替换-
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }

            catch (System.Exception ex)
            {

            }
            return strResult;
        }

        #endregion
    }
}